package com.wyp.controller.admin;

import com.wyp.User.User;
import com.wyp.pojo.Admins;
import com.wyp.pojo.Apartments;
import com.wyp.service.impl.AdminsServiceImpl;
import com.wyp.service.impl.ApartmentsServiceImpl;
import com.wyp.service.impl.QuestionsServiceImpl;
import com.wyp.service.impl.ScoresServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminLoginController {
    @Autowired
    private AdminsServiceImpl adminsService;

    @Autowired
    private QuestionsServiceImpl questionsService;

    @Autowired
    private ScoresServiceImpl scoresService;

    @Autowired
    private ApartmentsServiceImpl apartmentsService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @RequestMapping("/admin_logout.html")
    public String logout() {
        return "redirect:/admin/admin_login.html";
    }

    @GetMapping("/admin_login.html")
    public String tologin() {
        return "admin/admin_login";
    }

    @RequestMapping("/admin_error.html")
    public String toerror(HttpServletRequest request, Model model) {
        AuthenticationException exception =
                (AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        model.addAttribute("lerrormsg", exception.getMessage());
        return "admin/admin_login";
    }

    @RequestMapping("/admin_index.html")
    public String toIndex(
            Model model,
            HttpSession session) {
//        if (session.getAttribute("admin") == null) {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        if (auth.getPrincipal() instanceof User) {
            User user = (User) auth.getPrincipal();
            if (("ROLE_STU").compareTo((String.valueOf(((List) user.getAuthorities()).get(0)))) != 0) {
                Map<String, Integer> count = adminsService.GetDataCount();
                List<Apartments> apartments = apartmentsService.qureyAllApartment();
                int num = apartments.size();
                List<List<Map<String, Object>>> questions = new ArrayList<>();
                for (int i = 1; i <= num; i++) {
                    questions.add(questionsService.qureyQuestionsByApartmentname(i));
                }
                List<Integer> Qsum = new ArrayList<>();
                for (int i = 0; i < num * 3; i++) {
                    Qsum.add(0);
                }
                int apartcount = 0;
                for (List<Map<String, Object>> question : questions) {
                    if (question != null) {
                        for (Map<String, Object> questionbyapart : question) {
                            if ((int) questionbyapart.get("type") == 1) {
                                int i = Qsum.get(apartcount);
                                i++;
                                Qsum.set(apartcount, i);
                            }
                            if ((int) questionbyapart.get("type") == 2) {
                                int i = Qsum.get(apartcount + 1);
                                i++;
                                Qsum.set(apartcount + 1, i);
                            }
                            if ((int) questionbyapart.get("type") == 3) {
                                int i = Qsum.get(apartcount + 2);
                                i++;
                                Qsum.set(apartcount + 2, i);
                            }
                        }
                        apartcount += 3;
                    }
                }
                List<Map<String, Object>> scores = scoresService.qureyAllScores();
                List<Integer> scount = new ArrayList<>();
                List<Double> s = new ArrayList<>();
                for (int i = 0; i < 4; i++) {
                    scount.add(0);
                }
                int sum = 0;
                for (Map<String, Object> score : scores) {
                    if ((((int) score.get("score") * 1.0) / ((int) score.get("totalscore") * 1.0)) < 0.6) {
                        int i = scount.get(0);
                        i++;
                        scount.set(0, i);
                    }
                    if ((((int) score.get("score") * 1.0) / ((int) score.get("totalscore") * 1.0)) >= 0.6 && ((((int) score.get("score") * 1.0) / ((int) score.get("totalscore") * 1.0))) < 0.8) {
                        int i = scount.get(1);
                        i++;
                        scount.set(1, i);
                    }
                    if ((((int) score.get("score") * 1.0) / ((int) score.get("totalscore") * 1.0)) >= 0.8 && ((((int) score.get("score") * 1.0) / ((int) score.get("totalscore") * 1.0))) < 0.9) {
                        int i = scount.get(2);
                        i++;
                        scount.set(2, i);
                    }
                    if ((((int) score.get("score") * 1.0) / ((int) score.get("totalscore") * 1.0)) >= 0.9) {
                        int i = scount.get(3);
                        i++;
                        scount.set(3, i);
                    }
                    sum++;
                }
                DecimalFormat df = new DecimalFormat("0.0000");
                for (int i = 0; i < 4; i++) {
                    s.add(Double.valueOf(df.format((scount.get(i) * 1.0) / sum)));
                }
                session.setAttribute("Apartments", apartments);
                session.setAttribute("Scount", s);
                session.setAttribute("questionNum", Qsum);
                session.setAttribute("count", count);
                session.setAttribute("admin", user);
                return "admin/admin_index";
            } else {
                return "admin/admin_login";
            }
        } else {
            return "admin/admin_login";
        }
//        } else {
//            Map<String, Integer> count = adminsService.GetDataCount();
//            session.setAttribute("count", count);
//            return "admin/admin_index";
//        }
    }


    @GetMapping("/admin_toupdate.html")
    public String toupdatestu(
            HttpSession session,
            Model model
    ) {
        User admin = (User) session.getAttribute("admin");
        Admins updateadmin = adminsService.findByAdminaccount(admin.getUsername());
        model.addAttribute("updateadmin", updateadmin);
        return "admin/admin_update";
    }


    @PostMapping("/admin_update.html")
    public String manupdate(
            HttpSession session,
            @RequestParam("adminPassword") String adminPassword,
            Model model
    ) {
        User admin = (User) session.getAttribute("admin");
        Admins admins = adminsService.findByAdminaccount(admin.getUsername());
        admins.setAdminpassword(encoder.encode(adminPassword));
        boolean addadmin = adminsService.updateAdmin(admins);
        return "redirect:/admin/admin_index.html";
    }
}